
package jdx_14_基于CAS的新锁;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class T04_ReentrantLock4 {
	//这个程序有点错误
	public static void main(String[] args) {
		Lock lock = new ReentrantLock();


		Thread t1 = new Thread(()->{
			try {
				lock.lock(); //如果使用的是这种方式，该线程是不会被打断的，而是一直沉睡下去
				System.out.println("t1 start");
				TimeUnit.SECONDS.sleep(Integer.MAX_VALUE);//一直沉睡
				System.out.println("t1 end");
			} catch (InterruptedException e) {
				System.out.println("interrupted!");
			} finally {
				lock.unlock();
			}
		});
		t1.start();

		Thread t2 = new Thread(()->{
			try {
				//lock.lock();
				lock.lockInterruptibly();//如果使用的是可被打断的方式，那么别的线程可以打断它并且拿到锁资源
				System.out.println("t2 start");
				TimeUnit.SECONDS.sleep(5);
				System.out.println("t2 end");
			} catch (InterruptedException e) {
				System.out.println("interrupted!");
			} finally {
				lock.unlock();
			}
		});
		t2.start();

		try {
			TimeUnit.SECONDS.sleep(1);
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		t2.interrupt();

	}
}
